
package com.cx.widget;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.cx.update.DownloadUtil;
import com.cx.update.FileUtils;
import com.cx.update.DownloadPrecentListener;
import com.cx.update.R;
import com.cx.update.UpdateTask;
import com.cx.update.UpdateUtils;


@SuppressLint("ViewConstructor")
public class CleverDialog extends PopupWindow implements DownloadPrecentListener,
        DownloadUtil.ApkDownloadListener {

    private Context mContext;

    private Handler mHandler;

    private View mParentView;

    private TextView tvTitle, tvUpdateInfo, tvDownloadNote;

    private Button btn1, btn2, btn3;

    private ProgressBar downloadBar;

    private LinearLayout downloadBarLayout;

    public static final int BTN_RESET = -1;

    public static final int BTN_INDEX_ALL = 0;

    public static final int BTN_INDEX_LEFT = 1;

    public static final int BTN_INDEX_CENTER = 2;

    public static final int BTN_INDEX_RIGHT = 3;

    private boolean isDownloading = false;
    
    private DialogDismissListener mListener;

    public CleverDialog(Context context, Handler handler, View parentView) {

        if (null == mContext) {
            mContext = context;
        }
        if (null == mHandler) {
            mHandler = handler;
        }
        if (null == mParentView) {
            mParentView = parentView;
        }
        init();
        setAnimationStyle(R.style.Dialog_Ainm);
    }

    /**
     * 
     */
    @SuppressWarnings("deprecation")
    private void init() {
        setBackgroundDrawable(new BitmapDrawable());
        setFocusable(true);
        setWindowLayoutMode(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        LinearLayout localLayout = (LinearLayout)LayoutInflater.from(mContext).inflate(
                R.layout.dialog_layout, null);
        tvTitle = (TextView)localLayout.findViewById(R.id.dialog_title);
       
        tvUpdateInfo = (TextView)localLayout.findViewById(R.id.update_info);
        
        tvDownloadNote = (TextView)localLayout.findViewById(R.id.download_note);
       
        btn1 = (Button)localLayout.findViewById(R.id.dialog_btn_1);
       
        btn2 = (Button)localLayout.findViewById(R.id.dialog_btn_2);
      
        btn3 = (Button)localLayout.findViewById(R.id.dialog_btn_3);
       
        downloadBar = (ProgressBar)localLayout.findViewById(R.id.download_bar);
        downloadBar.setMax(100);
        downloadBarLayout = (LinearLayout)localLayout.findViewById(R.id.progressbar_layout);
        setContentView(localLayout);
    }

    @Override
    public void dismiss() {
        if(null != mListener) {
            mListener.dialoDismiss();
            mListener = null;
        }
        super.dismiss();
    }

    /**
     * 鏄剧ず鎻愮ず淇℃伅
     */
    public void show(String title, String btn1Name, String btn2Name, String btn3Name,
            OnClickListener btn1Listener, OnClickListener btn2Listener, OnClickListener btn3Listener) {
        downloadBarLayout.setVisibility(View.GONE);
        tvUpdateInfo.setVisibility(View.GONE);
        if (null != mParentView && !isShowing()) {
            tvTitle.setText(title);
            if (!TextUtils.isEmpty(btn1Name) && null != btn1Listener) {
                btn1.setVisibility(View.VISIBLE);
                btn1.setText(btn1Name);
                btn1.setOnClickListener(btn1Listener);
            } else {
                btn1.setVisibility(View.GONE);
            }
            if (!TextUtils.isEmpty(btn2Name) && null != btn2Listener) {
                btn2.setVisibility(View.VISIBLE);
                btn2.setText(btn2Name);
                btn2.setOnClickListener(btn2Listener);
            } else {
                btn2.setVisibility(View.GONE);
            }
            if (!TextUtils.isEmpty(btn3Name) && null != btn3Listener) {
                btn3.setVisibility(View.VISIBLE);
                btn3.setText(btn3Name);
                btn3.setOnClickListener(btn3Listener);
            } else {
                btn3.setVisibility(View.GONE);
            }
            showAtLocation(mParentView, Gravity.CENTER, 0, 0);
            setBtnEnable(BTN_RESET);
        }
    }

    /**
     * 鏄剧ず鎻愮ず淇℃伅
     */
    public void show(String title, String btn1Name, String btn2Name, String btn3Name,
            OnClickListener btn1Listener, OnClickListener btn2Listener,
            OnClickListener btn3Listener, String updateInfo) {
        downloadBarLayout.setVisibility(View.GONE);
        tvUpdateInfo.setVisibility(View.GONE);
        if (null != mParentView && !isShowing()) {
            if (!TextUtils.isEmpty(updateInfo)) {
                tvUpdateInfo.setVisibility(View.VISIBLE);
                tvUpdateInfo.setText(updateInfo);
            }
            tvTitle.setText(title);
            if (!TextUtils.isEmpty(btn1Name) && null != btn1Listener) {
                btn1.setVisibility(View.VISIBLE);
                btn1.setText(btn1Name);
                btn1.setOnClickListener(btn1Listener);
            } else {
                btn1.setVisibility(View.GONE);
            }
            if (!TextUtils.isEmpty(btn2Name) && null != btn2Listener) {
                btn2.setVisibility(View.VISIBLE);
                btn2.setText(btn2Name);
                btn2.setOnClickListener(btn2Listener);
            } else {
                btn2.setVisibility(View.GONE);
            }
            if (!TextUtils.isEmpty(btn3Name) && null != btn3Listener) {
                btn3.setVisibility(View.VISIBLE);
                btn3.setText(btn3Name);
                btn3.setOnClickListener(btn3Listener);
            } else {
                btn3.setVisibility(View.GONE);
            }
            showAtLocation(mParentView, Gravity.CENTER, 0, 0);
            setBtnEnable(BTN_RESET);
        }
    }

    public void show() {
        if (null != mParentView && !isShowing()) {
            downloadBarLayout.setVisibility(View.GONE);
            tvUpdateInfo.setVisibility(View.GONE);
            showAtLocation(mParentView, Gravity.CENTER, 0, 0);
        }
    }

    public void show(boolean hideDownloadBar) {
        if (null != mParentView && !isShowing()) {
            downloadBarLayout.setVisibility(hideDownloadBar ? View.GONE : View.VISIBLE);
            tvUpdateInfo.setVisibility(View.GONE);
            showAtLocation(mParentView, Gravity.CENTER, 0, 0);
        }
    }

    public void showDownLoading(final String appName,final String packageName, OnClickListener btn1Listener,
            String downloadAddress) {
        if (null != mParentView && !isShowing() && null != btn1Listener) {
            isDownloading = true;
            tvUpdateInfo.setVisibility(View.GONE);
            downloadBarLayout.setVisibility(View.VISIBLE);
            btn1.setVisibility(View.VISIBLE);
            btn2.setVisibility(View.GONE);
            btn3.setVisibility(View.GONE);
            btn1.setText(mContext.getString(R.string.cancel));
            btn1.setOnClickListener(btn1Listener);
            showAtLocation(mParentView, Gravity.CENTER, 0, 0);
            setBtnEnable(BTN_RESET);
            if (TextUtils.isEmpty(appName) || TextUtils.isEmpty(downloadAddress)) {
                startUpdateOrangeTV(btn1Listener);
            } else {
                // MoreTV or else;
                startDownLoadAPK(appName,packageName, downloadAddress, this);
            }
        }
    }

    public void startDownLoadAPK(final String appName,final String packageName, final String downloadAddress,
            final DownloadUtil.ApkDownloadListener mDownloadListener) {
        setTitle(appName);
       // ToastHelper.fastToast(mContext, String.format(mContext.getString(R.string.apk_must_install), appName, appName));
        new Thread(new Runnable() {
            @SuppressLint({
                    "SdCardPath", "SimpleDateFormat"
            })
            @Override
            public void run() {
              
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    try {
                        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
                        String time = sf.format(new Date());
                        String save_path = Environment.getExternalStorageDirectory().getPath()
                                + "/" + "OrangeTV/DownLoad/";
                        File folder = new File(save_path);
                        if (!folder.exists()) {
                            folder.mkdirs();
                        }
                        String fileName = packageName + time + ".apk";
                        File downloadFile = new File(save_path + fileName);
                        if (downloadFile.exists()) {
                            int fileSize = FileUtils.parseIntData(mContext, downloadFile.getName());
                            if (fileSize == downloadFile.length()) {
                                mDownloadListener.downloadError(DownloadUtil.DOWNLOAD_FILE_EXIST);
                                FileUtils.startInstallApp(mContext, downloadFile.getAbsolutePath());
                            } else {
                                downloadFile.delete();
                                if (DownloadUtil.downloadFile(mContext, downloadAddress,
                                        downloadFile, mDownloadListener)) {
                                    mDownloadListener.downloadSuccess();
                                    FileUtils.startInstallApp(mContext,
                                            downloadFile.getAbsolutePath());
                                } else {
                                    mDownloadListener.downloadError(DownloadUtil.DOWNLOAD_FAILED);
                                }
                            }
                        } else {
                            mDownloadListener.start();
                            try {
                                File[] files = folder.listFiles();
                                // 鍒犳帀鏃х殑鏂囦欢
                                for (int i = 0; i < files.length; i++) {
                                    if (files[i].getName().startsWith(
                                            packageName)) {
                                        files[i].delete();
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            if (DownloadUtil.downloadFile(mContext, downloadAddress, downloadFile,
                                    mDownloadListener)) {
                                FileUtils.startInstallApp(mContext, downloadFile.getAbsolutePath());
                                mDownloadListener.downloadSuccess();
                            } else {
                                mDownloadListener.downloadError(DownloadUtil.DOWNLOAD_FAILED);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        mDownloadListener.downloadError(DownloadUtil.DOWNLOAD_FAILED);
                    }
                } else {
                    mDownloadListener.downloadError(DownloadUtil.DOWNLOAD_SD_CARD_ERROR);
                }
            }
        }).start();
    }

    public boolean isDownloading() {
        return isDownloading;
    }

    public void startUpdateOrangeTV(OnClickListener onClickListener) {
        setTitle(mContext.getString(R.string.app_name));
        btn1.setOnClickListener(onClickListener);
        if (null != mHandler) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    UpdateUtils mUpdateUtils = new UpdateUtils();
                    mUpdateUtils.setDownloadPrecentListener(CleverDialog.this);
                    int result = mUpdateUtils.startDownload(UpdateTask.downloadAddress,
                           null, UpdateTask.downloadMd5+".apk",
                            UpdateTask.downloadMd5);
                    String path = mUpdateUtils.getFileSavePath();
                    System.out.println(result+"==path========"+path);
                    if (!TextUtils.isEmpty(path) && result == UpdateUtils.DOWNLOAD_SUCCESS) {
                        Message msg = new Message();
                        msg.what = UpdateTask.MSG_ORANGETV_NEED_INSTALL;
                        msg.obj = path;
                        mHandler.sendMessage(msg);
                    } else {
                        String reason = mContext.getString(R.string.download_no_save_path);
                        switch (result) {
                            case UpdateUtils.DOWNLOAD_SUCCESS:
                                reason = mContext.getString(R.string.download_no_save_path);
                                break;
                            case UpdateUtils.DOWNLOAD_CONNECT_ERROR:
                            case UpdateUtils.DOWNLOAD_TIME_OUT:
                            case UpdateUtils.DOWNLOAD_NO_INPUTSTREAM:
                                reason = mContext.getString(R.string.download_connect_failed);
                                break;
                            case UpdateUtils.DOWNLOAD_ERROR_FILE:
                                reason = mContext.getString(R.string.download_file_error);
                                break;
                            default:
                                reason = mContext.getString(R.string.download_no_save_path);
                                break;
                        }
                        Message msg = new Message();
                        msg.what = UpdateTask.MSG_ORANGETV_DOWNLOAD_ERROR;
                        msg.obj = reason;
                        mHandler.sendMessage(msg);
                    }
                    isDownloading = false;
                }
            }).start();
        }
    }

    public void setProcess(int index) {
        if (null != mParentView && isShowing()) {
            if (index < 100) {
                downloadBar.setProgress(index);
            } else if (index < 1) {
                downloadBar.setProgress(1);
            } else {
                downloadBar.setProgress(100);
            }
        }
    }

    public void close() {
        mParentView = null;
    }

    public void setBtnEnable(int index) {
        switch (index) {
            case BTN_INDEX_LEFT:
                btn1.setEnabled(false);
                break;
            case BTN_INDEX_CENTER:
                btn2.setEnabled(false);
                break;
            case BTN_INDEX_RIGHT:
                btn3.setEnabled(false);
                break;
            case BTN_INDEX_ALL:
                btn1.setEnabled(false);
                btn2.setEnabled(false);
                btn3.setEnabled(false);
                break;
            default:
                btn1.setEnabled(true);
                btn2.setEnabled(true);
                btn3.setEnabled(true);
                break;
        }
    }

    public boolean changeBtn(int index, String btnText, OnClickListener listener) {
        if (isShowing()) {
            switch (index) {
                case BTN_INDEX_LEFT:
                    if (!TextUtils.isEmpty(btnText) && null != listener) {
                        btn1.setText(btnText);
                        btn1.setOnClickListener(listener);
                    }
                    break;
                case BTN_INDEX_CENTER:
                    if (!TextUtils.isEmpty(btnText) && null != listener) {
                        btn2.setText(btnText);
                        btn2.setOnClickListener(listener);
                    }
                    break;
                case BTN_INDEX_RIGHT:
                    if (!TextUtils.isEmpty(btnText) && null != listener) {
                        btn3.setText(btnText);
                        btn3.setOnClickListener(listener);
                    }
                    break;
                default:
                    break;
            }
        }
        return false;
    }

    public void setTitle(String title) {
        if (isShowing() && null != tvTitle) {
            tvTitle.setText(title);
        }
    }
    
    public void setDismissListener(DialogDismissListener listener){
        mListener = listener;
    }

    @Override
    public void downloadSuccess() {
        setProcess(100);
        isDownloading = false;
    }

    @Override
    public void setDownloadedSize(int arg0, int arg1, float arg2) {
        setProcess((int)(((float)arg0 / (float)arg1) * 100));
    }

    @Override
    public void startDownload() {
        isDownloading = true;
    }

    @Override
    public void start() {
        // TODO Auto-generated method stub
        isDownloading = true;
    }

    @Override
    public void step(int step) {
        // TODO Auto-generated method stub
        setProcess(step);
    }

    @Override
    public void downloadError(int result) {
        if (result == 0) {
            setTitle(mContext.getString(R.string.download_file_exist));
        } else {
            setTitle(mContext.getString(R.string.download_failed) + result);
        }
        isDownloading = false;
    }

    public interface DialogDismissListener {
        void dialoDismiss();
    }

}
